package crm8000.Controllers

import crm8000.services.PermissionService;
import crm8000.services.SupplierService;
import crm8000.services.UserService;
import grails.converters.JSON

class SupplierController {
	static allowedMethods = [categoryList: 'POST', editCategory: 'POST', deleteCategory: 'POST',
		supplierList: 'POST', editSupplier: 'POST', deleteSupplier: 'POST',
		queryData: 'POST']

	PermissionService permissionService

	UserService userService
	
	SupplierService supplierService

	def index() {
		if (!permissionService.hasPermission('1004')) {
			redirect controller: 'home'
		}

		[loginUserName: userService.loginUserName]
	}

	def categoryList() {
		def data = supplierService.categoryList()
		
		render(contentType: "application/json") { array {
			for (c in data) {
				category id: c.id, code: c.code, name: c.name
			}
		}}
	}
	
	def editCategory() {
		def result = supplierService.editCategory(params)
		
		render result as JSON
	}
	
	def deleteCategory() {
		def result = supplierService.deleteCategory(params.id)
		
		render result as JSON
	}
	
	def supplierList() {
		def data = supplierService.supplierList(params.id)
		
		render(contentType: "application/json") { array {
			for (c in data) {
				supplier id: c.id, code: c.code, name: c.name, tel: c.tel, qq: c.qq, categoryId: c.category.id
			}
		}}

	}
	
	def editSupplier() {
		def result = supplierService.editSupplier(params)
		
		render result as JSON
	}
	
	def deleteSupplier() {
		def result = supplierService.deleteSupplier(params.id)
		
		render result as JSON
	}
	
	def queryData() {
		def data = supplierService.queryData(params.queryKey)
		render(contentType: "application/json") { array {
			for (c in data) {
				supplier id: c.id, code: c.code, name: c.name
			}
		}}
	}
}
